package jee.boot.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class VerificationCodeUtil {
    private static final Logger logger = LoggerFactory.getLogger(VerificationCodeUtil.class);
    /**
     * 验证码有效期5分钟
     */
    private static Integer timeout = 5;
    private static String STR_NUM = "0123456789";
    private static String STR_CHAR = "123456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";

    /**
     * 获取验证码
     *
     * @param length
     * @return
     */
    public static String getVerificationCode(int length) {
        String verificationCode = getCode(length, STR_CHAR);
        return verificationCode;
    }

    /**
     * 获取数字验证码
     *
     * @param length
     * @return
     */
    public static String getVerificationNum(int length) {
        String verificationCode = getCode(length, STR_NUM);
        return verificationCode;
    }

    /*
     * 定义一个获取随机验证码的方法：getCode();
     */
    private static String getCode(int n, String string) {
        // 声明一个字符数组对象ch 保存 验证码
        char[] ch = new char[n];

        for (int i = 0; i < n; i++) {
            // 创建一个新的随机数生成器
            Random random = new Random();

            // 返回[0,string.length)范围的int值    作用：保存下标
            int index = random.nextInt(string.length());

            // charAt() : 返回指定索引处的 char 值   ==》保存到字符数组对象ch里面
            ch[i] = string.charAt(index);
        }

        // 将char数组类型转换为String类型保存到result
        return String.valueOf(ch);
    }

    /**
     *  检查code是否匹配
     * @param redisKey
     * @param code
     * @return
     */
    public static boolean checkCode(String redisKey, String code) {
        return checkCode(redisKey, code, true);
    }

    /**
     * 检查code是否匹配
     *
     * @param redisKey
     * @param code
     * @return
     */
    public static boolean checkCode(String redisKey, String code, boolean removeCache) {
        if (StringUtils.isNotBlank(redisKey)) {
            String cacheCode = (String) getRedisTemplate().opsForValue().get(redisKey);
            if (StringUtils.isNotBlank(cacheCode)) {
                if (removeCache) {
                    //check 之后为了安全需要删除redis里面的 code
                    getRedisTemplate().delete(redisKey);
                }
            }
            if (code != null && StringUtils.equalsIgnoreCase(code, cacheCode)) {
                return true;
            }

        }
        return false;
    }

    /**
     * 删除缓存
     *
     * @param redisKey
     */
    public static void removeCacheKey(String redisKey) {
        getRedisTemplate().delete(redisKey);
    }

    /**
     * 缓存code
     *
     * @param code
     */
    public static String cacheCode(String code) {
        UUID randomUUID = UUID.randomUUID();
        String redisKey = randomUUID.toString();
        logger.info("缓存验证码 code=" + code + ";redisKey=" + redisKey);
        // 默认图片验证码有效时间 ：5 分钟
        getRedisTemplate().opsForValue().set(redisKey, code, timeout, TimeUnit.MINUTES);
        return redisKey;
    }

    public static RedisTemplate<String, Object> getRedisTemplate() {
        return SpringContextHolder.getApplicationContext().getBean(RedisTemplate.class);
    }

}
